import { nextTick } from "vue";
import IComponentServer from "../IComponentServer";



import { imStore } from "@/store/imStore";
import { userData as userDataStore } from "@/store/userData";

//const userDataStore = userDataStore();
var timesr: any = NaN,
    throttleFlag: boolean;
function throttle(func: Function, wait = 500, immediate = true) {
    if (immediate) {
        if (!throttleFlag) {
            throttleFlag = true;
            // 如果是立即执行，则在wait毫秒内开始时执行
            typeof func === "function" && func();
            timesr = setTimeout(() => {
                throttleFlag = false;
            }, wait);
        }
    } else {
        if (!throttleFlag) {
            throttleFlag = true;
            // 如果是非立即执行，则在wait毫秒内的结束处执行
            timesr = setTimeout(() => {
                throttleFlag = false;
                typeof func === "function" && func();
            }, wait);
        }
    }
}

/**
 * class TUIChatServer
 *
 * TUIChat 逻辑主体
 */
export default class TUIChatServer extends IComponentServer {
  public TUICore: any;
  public currentStore: any = {};
  public imStore:any;
  public userData:any;
  public noDel = 0;
  public lastMsgTime = 0;
  public isSlide = false;//是否在滑动
  public slideList:any = [] //滑动期间的消息
  //public timerSlide:any = null
  constructor(TUICore: any) {
    super();
    this.TUICore = (uni as any).$TUIKit;
    this.bindTIMEvent();
    //this.updateStore();
  }

  /**
   * 组件销毁
   */
  public destroyed() {
    this.unbindTIMEvent();
  }

  /**
   * 数据监听回调
   *
   * @param {any} newValue 新数据
   * @param {any} oldValue 旧数据
   *
   */
  public async updateStore() {

    const IM_STORE:any = imStore();
    IM_STORE.resetChat();
    this.lastMsgTime = Math.round(new Date().getTime()/1000);
    await this.initMessageList({
      conversationID: IM_STORE.conversationID
      //count: 15,
    });
  }

  /**
   * /////////////////////////////////////////////////////////////////////////////////
   * //
   * //                                    TIM 事件监听注册接口
   * //
   * /////////////////////////////////////////////////////////////////////////////////
   */

  private bindTIMEvent() {
    this.TUICore.on(
      uni.$TIM.EVENT.MESSAGE_RECEIVED,
      this.handleMessageReceived,
      this
    );
    this.TUICore.on(
      uni.$TIM.EVENT.MESSAGE_MODIFIED,
      this.handleMessageModified,
      this
    );
    this.TUICore.on(
      uni.$TIM.EVENT.MESSAGE_REVOKED,
      this.handleMessageRevoked,
      this
    );
    this.TUICore.on(
      uni.$TIM.EVENT.MESSAGE_READ_BY_PEER,
      this.handleMessageReadByPeer,
      this
    );
    // this.TUICore.on(
    //   uni.$TIM.EVENT.GROUP_LIST_UPDATED,
    //   this.handleGroupListUpdated,
    //   this
    // );
  }

  private unbindTIMEvent() {
    this.TUICore.off(
      uni.$TIM.EVENT.MESSAGE_RECEIVED,
      this.handleMessageReceived
    );
    this.TUICore.off(
      uni.$TIM.EVENT.MESSAGE_MODIFIED,
      this.handleMessageModified
    );
    this.TUICore.off(uni.$TIM.EVENT.MESSAGE_REVOKED, this.handleMessageRevoked);
    this.TUICore.off(
      uni.$TIM.EVENT.MESSAGE_READ_BY_PEER,
      this.handleMessageReadByPeer
    );
    // this.TUICore.off(
    //   uni.$TIM.EVENT.GROUP_LIST_UPDATED,
    //   this.handleGroupListUpdated,
    //   this
    // );
  }

  public handleScrollBottom(){
    uni.$emit('handleScrollBottom');
  }
  public systemNotice(data:any){
    uni.$emit('systemNotice',data);
  }
  public newMessage(data:any){
	  uni.$emit('newMessage',data);
  }
  //开始滑动
  public startCache (){
	  this.isSlide = true
	  //clearTimeout(this.timerSlide);
	  //this.timerSlide = null;
	  
  }
  //结束滑动
  public endCache (){
		
		const list = JSON.parse(JSON.stringify(this.slideList))
		this.isSlide = false
		this.slideList = []
		//this.timerSlide = setTimeout(() => {
		const IM_STORE:any = imStore();
		list.forEach((event:any) => {
			event.data.forEach((item:any) => {
				//console.log("监听新消息")
				//console.log(item)
				if (item.conversationID === IM_STORE.conversationID) {
					//const messageList = [...IM_STORE.messageList, item];
					// 更新 messageList
					IM_STORE.pushMessageList(item)
					uni.$emit('recivedNewMsg',item)
					this.newMessage(item);
					IM_STORE.plusMessageQuantity()
				  // nextTick(()=>{
				  //     throttle(this.handleScrollBottom,300,true);
				  // })
				}
				//系统通知处理
				if (item.conversationID == "@TIM#SYSTEM") {
					this.systemNotice(item)
				}
			});
		})
		//this.handleScrollBottom();
		/*
		uni.$TUIKit.TUIConversationServer.setMessageRead(IM_STORE.conversationID);
		*/
		//},500)
  }
  private handleMessageReceived(event: any) {
	if(!this.isSlide){
		const IM_STORE:any = imStore();
		event.data.forEach((item:any) => {
			//console.log("监听新消息")
			//console.log(item)
			if (item.conversationID === IM_STORE.conversationID) {
				//const messageList = [...IM_STORE.messageList, item];
				// 更新 messageList
				IM_STORE.pushMessageList(item)
				uni.$emit('recivedNewMsg',item)
				this.newMessage(item);
				this.handleScrollBottom();
				IM_STORE.plusMessageQuantity()
				// nextTick(()=>{
				//     throttle(this.handleScrollBottom,300,true);
				// })
			}
		  //系统通知处理
		  if (item.conversationID == "@TIM#SYSTEM") {
			  this.systemNotice(item)
		  }
		});
		/*
		uni.$TUIKit.TUIConversationServer.setMessageRead(IM_STORE.conversationID);
		*/
	}else{
		this.slideList.push(event)
	}
    
  }
  private handleMessageModified(event: any) {
    const IM_STORE:any = imStore();
    const middleData = IM_STORE.messageList;
    IM_STORE.messageList = [];
    IM_STORE.messageList = middleData;
  }
  private handleMessageRevoked(event: any) {
    // console.log('handleMessageRevoked')
    // console.log('handleMessageRevoked')
    // console.log('handleMessageRevoked')
    // console.log('handleMessageRevoked')
    // console.log(event);
    // const IM_STORE:any = imStore();
    // IM_STORE.updateRevoke(event.data)

    // const middleData = this.imStore.messageList;
    // this.imStore.messageList = [];
    // this.imStore.messageList = middleData;
  }
  private async handleMessageReadByPeer(event: any) {
    // sdk message 消息引用关系会自动更新
    const IM_STORE:any = imStore();
    const middleData = IM_STORE.messageList;
    // 兼容小程序，在小程序中 setData 是异步
    IM_STORE.resetChat()
    IM_STORE.setMessageList(middleData)
  }

  private handleGroupListUpdated(event: any) {
    const IM_STORE:any = imStore();
    event?.data.map((item: any) => {
      if (item?.groupID === IM_STORE?.conversation?.groupProfile?.groupID) {
        IM_STORE.conversation.groupProfile = item;
        const midden = IM_STORE.conversation;
        IM_STORE.conversation = {};
        IM_STORE.conversation = midden;
      }
      return item;
    });
  }

  /**
   * /////////////////////////////////////////////////////////////////////////////////
   * //
   * //                                 处理 TIM 接口参数及回调
   * //
   * /////////////////////////////////////////////////////////////////////////////////
   */

  /**
   * 创建消息生成参数
   *
   * @param {Object} content 消息体
   * @param {String} type 消息类型 text: 文本类型 file: 文件类型 face: 表情 location: 地址 custom: 自定义 merger: 合并 forward: 转发
   * @param {Callback} callback 回调函数
   * @param {any} to 发送的对象
   * @returns {options} 消息参数
   */
  public handleMessageOptions(
    content: any,
    type: string,
    callback?: any,
    to?: any
  ) {

    const IM_STORE:any = imStore();
    const options: any = {
      to: "",
      conversationType: to?.type || IM_STORE.conversation.type,
      payload: content,
      needReadReceipt: true,
    };
    
    if (type === "file" && callback) {
      options.onProgress = callback;
    }
    switch (options.conversationType) {
      case uni.$TIM.TYPES.CONV_C2C:
        options.to =
          to?.userProfile?.userID ||
          IM_STORE.conversation?.userProfile?.userID ||
          "";
        break;
      case uni.$TIM.TYPES.CONV_GROUP:
        options.to =
          to?.groupProfile?.groupID ||
          IM_STORE.conversation?.groupProfile?.groupID ||
          "";
        break;
      default:
        break;
    }
    return options;
  }

  /**
   * 处理异步函数
   *
   * @param {callback} callback 回调函数
   * @returns {Promise} 返回异步函数
   */
  public handlePromiseCallback(callback: any) {
    return new Promise<void>((resolve, reject) => {
      // const config = {
      //   TUIName: 'TUIChat',
      //   callback: () => {
      //     callback && callback(resolve, reject);
      //   },
      // };
      // this.TUICore.setAwaitFunc(config.TUIName, config.callback);
    });
  }

  /**
   * 文件上传进度函数处理
   *
   * @param {number} progress 文件上传进度 1表示完成
   * @param {message} message 文件消息
   */
  public handleUploadProgress(progress: number, message: any) {
    const IM_STORE:any = imStore();
    IM_STORE.messageList.map((item: any) => {
      if (item.ID === message.ID) {
        item.progress = progress;
      }
      return item;
    });
  }

  /**
   * /////////////////////////////////////////////////////////////////////////////////
   * //
   * //                                 对外方法
   * //
   * /////////////////////////////////////////////////////////////////////////////////
   */

  public sendMessage(message: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {


        // console.log('sendMessage')
        // console.log('sendMessage')
        // console.log('sendMessage')
        // console.log(JSON.parse(JSON.stringify(message));)

        let {conversationID,conversationType,from } = message;
        // const IM_STORE:any = imStore();
        // console.log(IM_STORE.conversation)

        // let title = '';

        // let  description = '';


        if(conversationType==='C2C'){
            conversationID = `${conversationType}${from}`
        }
        // if(conversationType==='GROUP'){
        //     title = IM_STORE.conversation.groupProfile.name;
        //     description = `${nick}:`
        // }



        

        

        // if(type===uni.$TIM.TYPES.MSG_TEXT){
        //     description += payload.text;
        // }
        // if(type===uni.$TIM.TYPES.MSG_IMAGE){
        //     description = '[图片] ';
        // }
        // if(type===uni.$TIM.TYPES.MSG_VIDEO){
        //     description = '[视频] ';
        // }
        // if(type===uni.$TIM.TYPES.MSG_AUDIO){
        //     description = '[语音] ';
        // }




        const imResponse = await this.TUICore.sendMessage(message,{
            offlinePushInfo: {
                // title, // 离线推送标题
                // description, // 离线推送内容
                ignoreIOSBadge:false,
                androidOPPOChannelID: '',// 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
                extension: JSON.stringify({
                    entity: { // entity 中的内容可自定义
                        type:'chat',
                        conversationID,
                    }
                })
            }
        });


        resolve(imResponse);
      } catch (error) {
        console.log('eeeeeeeeee11111111')
        console.log('eeeeeeeeee11111111')
        console.log('eeeeeeeeee11111111')
        console.log(error);
        reject(error);
      }
    });
  }

  // /**
  //  * 发送文本消息
  //  *
  //  * @param {any} text 发送的消息
  //  * @returns {Promise}
  //  */
  /**
   * 发送文本消息
   *
   * @param {any} text 发送的消息
   * @returns {Promise}
   */
  public sendTextMessage(text: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      let message = null
    
      try {
        const options = this.handleMessageOptions({ text }, "text");
        message = this.TUICore.createTextMessage(options);
        const IM_STORE:any = imStore();
        // 优化写法
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)
        console.log('sendTextMessage')
        const imResponse = await this.sendMessage(message);
        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
          if (item.ID === imResponse.data.message.ID) {
            return imResponse.data.message;
          }
          return item;
        });

        // console.log('sendTextMessage imResponse')
        // console.log('sendTextMessage imResponse')
        // console.log('sendTextMessage imResponse')
        // console.log(imResponse)

        resolve(imResponse);
      } catch (error) {



        setTimeout(() =>{
            error.data.message.failReason = error.code
            const IM_STORE:any = imStore();


            IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
                if (item.ID === error.data.message.ID) {
                return error.data.message;
                }
                return item;
            });
            setTimeout(()=>{
                uni.$emit('recalcHeight')
            },300)


        },500)

        reject(error);
      }
    });
  }


  /**
   * 发送表情消息
   *
   * @param {Object} data 消息内容
   * @param {Number} data.index 表情索引
   * @param {String} data.data 额外数据
   * @returns {Promise}
   */
  public sendFaceMessage(data: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const options = this.handleMessageOptions(data, "face");
        const message = this.TUICore.createFaceMessage(options);
        const IM_STORE:any = imStore();
        // this.imStore.messageList.push(message);
        // 优化写法
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)
        const imResponse = await this.sendMessage(message);
        const arr = IM_STORE.messageList.map((item: any) => {
          if (item.ID === imResponse.data.message.ID) {
            return imResponse.data.message;
          }
          return item;
        });

        IM_STORE.setMessageList(arr)

        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 发送图片消息
   *
   * @param {res} res 图片文件
   * @param {image} 图片尺寸
   * @returns {Promise}
   */
  public sendImageMessage(res: any, image: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {
		//console.log(res)
        const options = this.handleMessageOptions({ file: res }, "file");
        const message = this.TUICore.createImageMessage(options);
        // todo  上屏图片消息在发送之前没有尺寸，本地获取补充
        message.payload.imageInfoArray[1].height = image.height;
        message.payload.imageInfoArray[1].width = image.width;
        const IM_STORE:any = imStore();
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)
        const imResponse = await this.sendMessage(message);
        const arr = IM_STORE.messageList.map((item: any) => {
			if (item.ID === imResponse.data.message.ID) {
				return imResponse.data.message;
			}
			return item;
        });

        IM_STORE.setMessageList(arr);
        resolve(imResponse);
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });

        reject(error);
      }
    });
  }

  /**
   * 发送视频消息
   *
   * @param {Video} video 图片文件
   * @returns {Promise}
   */
  public sendVideoMessage(res: any, video: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const options = this.handleMessageOptions({ file: res }, "file");
        const message = this.TUICore.createVideoMessage(options);
        const IM_STORE:any = imStore();
        // todo  上屏图片消息在发送之前没有尺寸，本地获取补充
        // message.payload.imageInfoArray[1].height = video.height
        // message.payload.imageInfoArray[1].width = video.width
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)
        const imResponse = await this.sendMessage(message);
        const arr = IM_STORE.messageList.map((item: any) => {
          if (item.ID === imResponse.data.message.ID) {
            return imResponse.data.message;
          }
          return item;
        });

        IM_STORE.setMessageList(arr);
        resolve(imResponse);
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });
        reject(error);
      }
    });
  }

  /**
   * 发送语音消息
   *
   * @param {audio} audio 音频文件
   * @returns {Promise}
   */
  public sendAudioMessage(audio: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const options = this.handleMessageOptions(
          { file: audio },
          "file",
          (progress: number) => {
            this.handleUploadProgress(progress, message);
          }
        );
        const IM_STORE:any = imStore();
        const message = this.TUICore.createAudioMessage(options);
        // todo  上屏图片消息在发送之前没有尺寸，待优化
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)
        const imResponse = await this.sendMessage(message);
        //console.log("发送音频消息完成", imResponse);
        const arr = IM_STORE.messageList.map((item: any) => {
          if (item.ID === imResponse.data.message.ID) {
            return imResponse.data.message;
          }
          return item;
        });

        IM_STORE.setMessageList(arr)

        resolve(imResponse);
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });

        reject(error);
      }
    });
  }

  /**
   * 发送文件消息
   *
   * @param {File} file 文件
   * @returns {Promise}
   */
  public sendFileMessage(file: any): Promise<any> {
    return this.handlePromiseCallback(async (resolve: any, reject: any) => {
      try {
        const options = this.handleMessageOptions(
          { file },
          "file",
          (progress: number) => {
            this.handleUploadProgress(progress, message);
          }
        );
        const message = this.TUICore.createFileMessage(options);
        const IM_STORE:any = imStore();
        this.currentStore.messageList.push(message);
        const imResponse = await this.sendMessage(message);
        //console.log("发送文件消息完成", imResponse);
        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
          if (item.ID === imResponse.data.message.ID) {
            return imResponse.data.message;
          }
          return item;
        });
        resolve(imResponse);
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });

        reject(error);
      }
    });
  }

  /**
   * 发送自定义消息
   *
   * @param {Object} data 消息内容
   * @param {String} data.data 自定义消息的数据字段
   * @param {String} data.description 自定义消息的说明字段
   * @param {String} data.extension 自定义消息的扩展字段
   * @returns {Promise}
   */
  public async sendCustomMessage(data: any){
      try {
        const options = this.handleMessageOptions(data, "custom");



        const message = this.TUICore.createCustomMessage(options);

        const IM_STORE:any = imStore();
        // 优化写法
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)





        const imResponse = await this.TUICore.sendMessage(message);
        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === imResponse.data.message.ID) {
              return imResponse.data.message;
            }
            return item;
        });


        } catch (error) {

            console.log(error);

            error.data.message.failReason = error.code
            const IM_STORE:any = imStore();


            IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
                if (item.ID === error.data.message.ID) {
                return error.data.message;
                }
                return item;
            });

        }

  }

  /**
   * 发送地理位置消息
   *
   * @param {Object} data 消息内容
   * @param {String} data.description 地理位置描述信息
   * @param {Number} data.longitude 经度
   * @param {Number} data.latitude 纬度
   * @returns {Promise}
   */
  public sendLocationMessage(data: any): Promise<any> {
    return this.handlePromiseCallback(async (resolve: any, reject: any) => {
      try {
        const options = this.handleMessageOptions(data, "location");
        const message = this.TUICore.createLocationMessage(options);
        const IM_STORE:any = imStore();
        IM_STORE.messageList.push(message);
        const imResponse = await this.TUICore.sendMessage(message);
        //console.log("发送地理位置消息完成", imResponse);
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 转发消息
   *
   * @param {message} message 消息实例
   * @param {any} to 转发的对象
   * @returns {Promise}
   */
  public async forwardMessage(message: any, to: any){

    console.log('forwardMessage')
    console.log('forwardMessage')
    console.log('forwardMessage')
    console.log('forwardMessage')

      try {
        const options = this.handleMessageOptions(message, "forward", {}, to);
        const imMessage = this.TUICore.createForwardMessage(options);
        const imResponse = await this.sendMessage(imMessage);
        const IM_STORE:any = imStore();
        if (
            IM_STORE.conversation.conversationID ===
          imResponse.data.message.conversationID
        ) {
            IM_STORE.messageList.push(imResponse.data.message);
        }
        //console.log("消息转发完成", imResponse);
        return Promise.resolve(imResponse)
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });

        return Promise.reject(error)
      }
  }

  /**
   * 发送@ 提醒功能的文本消息
   *
   * @param {Object} data 消息内容
   * @param {String} data.text 文本消息
   * @param {Array} data.atUserList 需要 @ 的用户列表，如果需要 @ALL，请传入 TIM.TYPES.MSG_AT_ALL
   * @returns {message}
   *
   * - 注：此接口仅用于群聊
   */
  public sendTextAtMessage(data: Object) {
    return new Promise<void>(async (resolve, reject) => {
      try {
        console.log('sendTextAtMessage')
        console.log('sendTextAtMessage')
        console.log('sendTextAtMessage')

        console.log(data)

        const options = this.handleMessageOptions(data, "text");
        const message = this.TUICore.createTextAtMessage(options);

        console.log(options)
        console.log(message)

        const IM_STORE:any = imStore();
        // 优化写法
        const messageList = [...IM_STORE.messageList, message];
        IM_STORE.setMessageList(messageList)
        const imResponse = await this.sendMessage(message);
        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
          if (item.ID === imResponse.data.message.ID) {
            return imResponse.data.message;
          }
          return item;
        });

        
        //atUserList: ['denny', 'lucy', TencentCloudChat.TYPES.MSG_AT_ALL]
        // this.currentStore.messageList.push(message);
        // const imResponse = await this.TUICore.sendMessage(message).catch((err)=>{
        //     console.log('errerrerrerr')
        //     console.log('errerrerrerr')
        //     console.log('errerrerrerr')
        //     console.log('errerrerrerr')
        //     console.log(err)
        // });

        // console.log('sssssssssss')
        // console.log('sssssssssss')
        // console.log(imResponse)

        // this.currentStore.messageList = this.currentStore.messageList.map(
        //   (item: any) => {
        //     if (item.ID === imResponse.data.message.ID) {
        //       return imResponse.data.message;
        //     }
        //     return item;
        //   }
        // );
        resolve(imResponse);
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });

        reject(error);
      }
    });
  }

  /**
   * 发送合并消息
   *
   * @param {Object} data 消息内容
   * @param {Array.<Message>} data.messageList 合并的消息列表
   * @param {String} data.title 合并的标题
   * @param {String} data.abstractList 摘要列表，不同的消息类型可以设置不同的摘要信息
   * @param {String} data.compatibleText 兼容文本
   * @returns {Promise}
   */
  public sendMergerMessage(data: any): Promise<any> {
    return this.handlePromiseCallback(async (resolve: any, reject: any) => {
      try {
        const options = this.handleMessageOptions(data, "merger");
        const message = this.TUICore.createMergerMessage(options);
        this.currentStore.messageList.push(message);
        const imResponse = await this.sendMessage(message);
        //console.log("发送合并消息完成", imResponse);
        this.currentStore.messageList = this.currentStore.messageList.map(
          (item: any) => {
            if (item.ID === imResponse.data.message.ID) {
              return imResponse.data.message;
            }
            return item;
          }
        );
        resolve(imResponse);
      } catch (error) {
        error.data.message.failReason = error.code
        const IM_STORE:any = imStore();


        IM_STORE.messageList = IM_STORE.messageList.map((item: any) => {
            if (item.ID === error.data.message.ID) {
              return error.data.message;
            }
            return item;
        });

        reject(error);
      }
    });
  }

  /**
   * 获取 messageList
   *
   * @param {any} options 获取 messageList 参数
   * @param {Boolean} history  是否获取历史消息
   * @returns {Promise}
   */
  public async initMessageList(options: any, history?: Boolean) {
		try {
			const imResponse = await this.TUICore.getMessageList(options);
			let messageList = [];
	
	
			imResponse.data.messageList.forEach(item=>{
				if(!item.isDelete&&!item.isRevoked) {
					this.noDel+=1;
				}
			})
	
	
			const IM_STORE:any = imStore();
			messageList = imResponse.data.messageList;
	
			// if (!history) {
			//   messageList = imResponse.data.messageList;
			// } else {
			//   messageList = [
			//     ...imResponse.data.messageList,
			//     ...IM_STORE.messageList,
			//   ];
			// }
			this.currentStore.nextReqMessageID = imResponse.data.nextReqMessageID;
			this.currentStore.isCompleted = imResponse.data.isCompleted;
	
			IM_STORE.setIsCompleted(imResponse.data.isCompleted)
	
	
			let oldMessageTime = messageList[0].time;
				messageList.forEach((item) => {
					if (item.time - oldMessageTime > 20 * 60) {
						oldMessageTime = item.time;
						item.showTime = true;
					} else {
						item.showTime = false;
					}
				});
	
	
	
	
	
			// if(!imResponse.data.isCompleted){
			//     let loadingMessage = {
			//         type:'loading',
			//         id:'first1989',
			//     }
			//     messageList.unshift(loadingMessage);
			// }
	
			messageList.reverse();
	
			for (let i = 0; i < messageList.length; i++) {
	
				let mes = messageList[i];
	
				// if ( this.lastMsgTime - mes.time > 5 * 60) {
				//     this.lastMsgTime = mes.time;
				//     mes.showTime = true;
				// }
	
				IM_STORE.unshiftMessageList(mes);
				// scrollID.value = null;
				// nextTick(() => {
				//     scrollID.value = lastId;
				// });
			}
	
			if(this.noDel>=13){
	
			}else{
	
	
				if(imResponse.data.isCompleted){
					return imResponse.data;
				}
				options.nextReqMessageID=this.currentStore.nextReqMessageID;
				await this.initMessageList(options)
			}
	
	
		  } catch (error) {
		  }
  }
  public async getMessageList(options: any, history?: Boolean) {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse = await this.TUICore.getMessageList(options);
        // let messageList;
        // const IM_STORE:any = imStore();
        // if (!history) {
        //   messageList = imResponse.data.messageList;
        // } else {
        //   messageList = [
        //     ...imResponse.data.messageList,
        //     ...IM_STORE.messageList,
        //   ];
        // }
        this.currentStore.nextReqMessageID = imResponse.data.nextReqMessageID;
        this.currentStore.isCompleted = imResponse.data.isCompleted;

        if(imResponse.data.messageList.length){


            let oldMessageTime = imResponse.data.messageList[0].time;
            imResponse.data.messageList.forEach((item:any) => {
                if (item.time - oldMessageTime > 10 * 60) {
                    oldMessageTime = item.time;
                    item.showTime = true;
                } else {
                    item.showTime = false;
                }
            });

            // imResponse.data.messageList.reverse();

            // imResponse.data.messageList.forEach((item) => {
            //     if ( this.lastMsgTime - item.time > 5 * 60) {
            //         this.lastMsgTime = item.time;
            //         item.showTime = true;
            //     } 
            // });

            // imResponse.data.messageList.reverse();
        }


        // IM_STORE.setMessageList(messageList)
        resolve(imResponse.data);
      } catch (error) {
        reject(error);
      }
    });
  }
  

  /**
   * 获取历史消息
   *
   * @returns {Promise}
   */
  public async getHistoryMessageList() {
    return new Promise<void>(async (resolve, reject) => {
      try {
		
        const IM_STORE:any = imStore();

        const options = {
          conversationID: IM_STORE.conversation.conversationID,
          nextReqMessageID: this.currentStore.nextReqMessageID,
          count: 22,
        };
        let obj:any = {
            nextReqMessageID:null,
            isCompleted:this.currentStore.isCompleted,
            messageList:[],

        };
        if (!this.currentStore.isCompleted) {
            obj = await this.getMessageList(options, true);
        }


        resolve(obj);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 消息撤回
   *
   * @param {message} message 消息实例
   * @returns {Promise}
   */
  public revokeMessage(message: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse = await this.TUICore.revokeMessage(message);
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 重发消息
   *
   * @param {message} message 消息实例
   * @returns {Promise}
   */
  public resendMessage(message: any): Promise<any> {
    return new Promise<void>(async (resolve, reject) => {
      try {
        const imResponse = await this.TUICore.resendMessage(message);
        //const IM_STORE:any = imStore();



        console.log("消息重发完成", imResponse);
		
        // messageList = IM_STORE.messageList.map(
        //   if(item)
        // );
        // IM_STORE.setMessageList(messageList)
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 删除消息
   *
   * @param {Array.<message>} messages 消息实例
   * @returns {Promise}
   */
  public deleteMessage(messages: any): Promise<any> {
    console.log('deleteMessage')
    console.log(messages)
    return new Promise<void>(async (resolve, reject) => {
      try {
        const IM_STORE:any = imStore();
        const imResponse = await this.TUICore.deleteMessage(messages);
				let messageList = [];
				messageList = IM_STORE.messageList.filter(
				  (item: any) => item.ID !== messages.ID
				);
        IM_STORE.setMessageList(messageList);
        resolve(imResponse);
      } catch (error) {
        reject(error);
      }
    });
  }
}
